const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const { exec } = require('child_process');
const fs = require('fs');
const path = require('path');
const { v4: uuidv4 } = require('uuid');

const app = express();
const PORT = process.env.PORT || 3000;

// 中间件
app.use(cors());
app.use(bodyParser.json());
app.use(express.static('public'));

// 存储临时文件
const TEMP_DIR = path.join(__dirname, 'temp');
if (!fs.existsSync(TEMP_DIR)) {
    fs.mkdirSync(TEMP_DIR);
}

// 清理临时文件
function cleanupTempFiles() {
    if (fs.existsSync(TEMP_DIR)) {
        const files = fs.readdirSync(TEMP_DIR);
        files.forEach(file => {
            const filePath = path.join(TEMP_DIR, file);
            if (fs.statSync(filePath).mtime < Date.now() - 5 * 60 * 1000) {
                fs.unlinkSync(filePath);
            }
        });
    }
}

// 每5分钟清理一次临时文件
setInterval(cleanupTempFiles, 5 * 60 * 1000);

// 编译并运行C++代码
app.post('/api/run', (req, res) => {
    const { code } = req.body;
    
    if (!code || code.trim() === '') {
        return res.status(400).json({ error: '代码不能为空' });
    }

    const fileId = uuidv4();
    const cppFile = path.join(TEMP_DIR, `${fileId}.cpp`);
    const exeFile = path.join(TEMP_DIR, fileId);

    // 写入C++源文件
    fs.writeFileSync(cppFile, code);

    // 编译C++代码
    const compileCmd = `g++ "${cppFile}" -o "${exeFile}"`;
    exec(compileCmd, (compileError, compileStdout, compileStderr) => {
        if (compileError) {
            fs.unlinkSync(cppFile);
            return res.json({
                success: false,
                error: compileStderr || '编译失败',
                output: ''
            });
        }

        // 运行编译后的程序
        const runCmd = `"${exeFile}"`;
        exec(runCmd, { timeout: 5000 }, (runError, runStdout, runStderr) => {
            // 清理文件
            try {
                fs.unlinkSync(cppFile);
                fs.unlinkSync(exeFile);
            } catch (e) {
                console.error('清理文件失败:', e);
            }

            if (runError) {
                return res.json({
                    success: false,
                    error: runStderr || '运行失败',
                    output: ''
                });
            }

            res.json({
                success: true,
                output: runStdout || '程序运行成功，但没有输出',
                error: runStderr || ''
            });
        });
    });
});

// 获取默认代码
app.get('/api/default-code', (req, res) => {
    const defaultCode = `#include <iostream>
using namespace std;

int main()
{
    cout << "Hello World";
    return 0;
}`;
    res.json({ code: defaultCode });
});

app.listen(PORT, () => {
    console.log(`服务器运行在 http://localhost:${PORT}`);
});
